package netty.http;

//import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION;
//import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
//import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory;
import io.netty.handler.codec.http.multipart.HttpDataFactory;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;

import java.net.URI;

import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

//import io.netty.handler.codec.http.HttpHeaders.Values;

/**
 * Auth: bruce-sha
 * Date: 2015/3/6
 */
public class HttpServerInboundHandler extends ChannelHandlerAdapter {


    private HttpRequest request;

    private static final HttpDataFactory factory =
            new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // Disk if size exceed

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        if (msg instanceof HttpRequest) {
            request = (HttpRequest) msg;

            HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(factory, request);
            while (decoder.hasNext()) {
                InterfaceHttpData hd = decoder.next();
                System.out.println(hd);
            }

            String uri = request.uri();
            System.out.println("Uri:" + uri);

            String referer = request.headers().getAndConvert("referer");
            System.out.println(referer);
            if (referer != null) {
                String refererURI = new URI(referer).getPath();
                System.out.println(refererURI);
            }
        }
        if (msg instanceof HttpContent) {
            HttpContent content = (HttpContent) msg;
            ByteBuf buf = content.content();
            System.out.println(buf.toString(io.netty.util.CharsetUtil.UTF_8));

//            http://kanpiaoxue.iteye.com/blog/2163332
//            QueryStringDecoder decoderQuery = new QueryStringDecoder("some?" + body);

            buf.release();


            String res = "I am OK";

            // 配置相关信息
            final String databaseName = "yBeHeL";
            final String host = "redis.duapp.com";
            final int port = 80;
            final String username = "8TAbwkckuyxq";// 用户名(api key);
            final String password = "HszPIhnaG9d";// 密码(secret key)
// 创建连接
//            Jedis jedis = new Jedis(host, port);
//            jedis.connect();
//            jedis.auth("");
//// 操作数据库
//            jedis.set("ibruce.info", "0");
            long counter = 1;//jedis.incr("ibruce.info");

// 准备输出
            QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());

            String jsonpCallback = queryStringDecoder.parameters().get("jsonpCallback").get(0);
            res = (String.format("try{%s(%s);}catch(e){}", jsonpCallback, counter));


            FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
                    OK, Unpooled.wrappedBuffer(res.getBytes("UTF-8")));
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().setLong(HttpHeaderNames.CONTENT_LENGTH,
                    response.content().readableBytes());
            if (HttpHeaderUtil.isKeepAlive(request)) {
                response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
            }
            ctx.write(response);
            ctx.flush();
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }


}
